package com.heima.admin.aop;


import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@RequiredArgsConstructor
@Component
public class AdminActionLogAspect {

    @Around("execution(* com.heima.admin.controller..*(..))  && @annotation(com.heima.admin.annotation.OperationLogAnnotation)") // Adjust the package name
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {


        long start = System.currentTimeMillis();

        // Get the current HTTP request using RequestContextHolder
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // Extract request headers via reflection
        Enumeration<String> headerNames = request.getHeaderNames();
        StringBuilder headers = new StringBuilder("Request Headers: ");

        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headers.append(headerName).append(" = ").append(headerValue).append("; ");
        }

        // Execute the method
        Object proceed = joinPoint.proceed();

        long executionTime = System.currentTimeMillis() - start;
        return proceed;
    }
}
